﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Controls;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.VisualStudio.Shell;
using System;
using System.ComponentModel.Composition;
using System.Drawing;
using System.IO;
using System.Reflection;
using TeamExplorer.Merge.Base;

namespace TeamExplorer.Merge.MergeCandidates
{
    [TeamExplorerNavigationItem(MergeCandidatesNavigationItem.LinkId, 1000)]
    public class MergeCandidatesNavigationItem : TeamExplorerBaseNavigationItem
    {
        public const string LinkId = "26E2C30D-93F3-4CF3-A98B-7BC219E1D56B";
        private UIContext tfsProviderContext;

        [ImportingConstructor]
        public MergeCandidatesNavigationItem([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            this.Text = "Merge Candidates";

            tfsProviderContext = UIContext.FromUIContextGuid(TeamExplorerBase.TfsProviderGuid);
            if (tfsProviderContext != null)
                tfsProviderContext.UIContextChanged += tfsProviderContext_UIContextChanged;
            SetVisibility();
            this.Image = GetImage();
        }

        private void SetVisibility()
        {
            this.IsVisible = tfsProviderContext != null && tfsProviderContext.IsActive;
        }

        void tfsProviderContext_UIContextChanged(object sender, UIContextChangedEventArgs e)
        {
            SetVisibility();
        }

        private Image GetImage()
        {
            Image mergeIcon = null;
            
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Resources\\Merge.ico");
            if (File.Exists(path))
                mergeIcon = Image.FromFile(path);

            return mergeIcon;
        }

        public override void Execute()
        {
            var teamExplorer = GetService<ITeamExplorer>();
            teamExplorer.NavigateToPage(new Guid(MergeCandidatesPage.PageId), null);
        }
    }
}
